package cn.jeeweb.web.modules.sys.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.jeeweb.common.mybatis.mvc.service.impl.CommonServiceImpl;
import cn.jeeweb.common.mybatis.mvc.wrapper.EntityWrapper;
import cn.jeeweb.common.utils.StringUtils;
import cn.jeeweb.web.modules.sys.entity.Dict;
import cn.jeeweb.web.modules.sys.entity.User;
import cn.jeeweb.web.modules.sys.entity.UserOrganization;
import cn.jeeweb.web.modules.sys.entity.UserRole;
import cn.jeeweb.web.modules.sys.mapper.UserMapper;
import cn.jeeweb.web.modules.sys.service.IDictService;
import cn.jeeweb.web.modules.sys.service.IUserOrganizationService;
import cn.jeeweb.web.modules.sys.service.IUserRoleService;
import cn.jeeweb.web.modules.sys.service.IUserService;
import cn.jeeweb.web.utils.PageRequest;
import cn.jeeweb.web.utils.UserUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Transactional
@Service("userService")
public class UserServiceImpl extends CommonServiceImpl<UserMapper, User> implements IUserService {
	@Autowired
	PasswordService passwordService;
	@Autowired
	private IUserOrganizationService userOrganizationService;
	@Autowired
	private IUserRoleService userRoleService;
	@Autowired
	private IDictService dictService;

	@Override
	public void changePassword(String userid, String newPassword) {
		User user = selectById(userid);
		if (user != null) {
			user.setPassword(newPassword);
			passwordService.encryptPassword(user);
		}
		insertOrUpdate(user);
	}

	@Override
	public User findByUsername(String username) {
		if (StringUtils.isEmpty(username)) {
			return null;
		}
		return selectOne(new EntityWrapper<User>(User.class).eq("username", username));
	}

	@Override
	public User findByEmail(String email) {
		if (StringUtils.isEmpty(email)) {
			return null;
		}
		return selectOne(new EntityWrapper<User>(User.class).eq("email", email));
	}

	@Override
	public User findByPhone(String phone) {
		if (StringUtils.isEmpty(phone)) {
			return null;
		}
		return selectOne(new EntityWrapper<User>(User.class).eq("phone", phone));
	}

	@Override
	public User findByCode(String code) {
		if (StringUtils.isEmpty(code)) {
			return null;
		}
		return selectOne(new EntityWrapper<User>(User.class).eq("code", code));
	}

	@Override
	public boolean deleteById(Serializable id) {
		// 删除角色关联
		userRoleService.delete(new EntityWrapper<UserRole>(UserRole.class).eq("userId", id));
		// 删除部门关联
		userOrganizationService.delete(new EntityWrapper<UserOrganization>(UserOrganization.class).eq("userId", id));
		return super.deleteById(id);
	}

	@Override
	public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
		for (Object id : idList) {
			this.deleteById((Serializable) id);
		}
		return true;
	}

	@Override
	public Page<User> selectPage(Page<User> page, Wrapper<User> wrapper) {
		wrapper.eq("1", "1");
		page.setRecords(baseMapper.selectUserList(page, wrapper));
		return page;
	}

	@Override
	public Boolean checkPassword(String userId, String password) {
		User user=selectById(userId);
		if (user==null){
			return Boolean.FALSE;
		}
		String newPassword=passwordService.getPassword(password,user.getCredentialsSalt());
		if (newPassword.equals(user.getPassword())){
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	@Override
	public Boolean insertUser(User user,HttpServletRequest request) {
		//账号重复
		if (selectCount(new EntityWrapper<User>().eq("username",user.getUsername()))>0){
			throw new RuntimeException("账号重复");
		}
		//检查手机号码
		if (selectCount(new EntityWrapper<User>().eq("phone",user.getPhone()))>0){
			throw new RuntimeException("手机号码重复");
		}
		String[] emails = user.getEmails();
		String email = "";
		if(emails != null && emails.length > 0){
			for(int i = 0;i<emails.length; i ++){
				if(i < emails.length -1){
					email = email + emails[i] +",";
				}else{
					email = email + emails[i];
				}
			}
		}
		user.setEmail(email);
		passwordService.encryptPassword(user);
		Boolean result = super.insert(user);
		afterSave(user);
		return result;
	}

	@Override
	public boolean insert(String json) {
		User user = JSON.parseObject(json,User.class);
		//账号重复
		if (selectCount(new EntityWrapper<User>().eq("username",user.getUsername()))>0){
			throw new RuntimeException("账号重复");
		}
		//检查手机号码
		if (selectCount(new EntityWrapper<User>().eq("phone",user.getPhone()))>0){
			throw new RuntimeException("手机号码重复");
		}
		String[] emails = user.getEmails();
		String email = "";
		if(emails != null && emails.length > 0){
			for(int i = 0;i<emails.length; i ++){
				if(i < emails.length -1){
					email = email + emails[i] +",";
				}else{
					email = email + emails[i];
				}
			}
		}
		user.setEmail(email);
		passwordService.encryptPassword(user);
		Boolean result = super.insert(user);
		afterSave(user);
		return result;
	}

	@Override
	public List<User> getUsersByOrgId(String organizationId) {
		return baseMapper.getUsersByOrgId(organizationId);
	}

	@Override
	public List<User> getUsersByGroupId(String organizationId) {
		return baseMapper.getUsersByGroupId(organizationId);
	}

	@Override
	public Boolean insertOrUpdateUser(User user, HttpServletRequest request) {
		//账号重复
		if (selectCount(new EntityWrapper<User>().ne("id",user.getId()).eq("username",user.getUsername()))>0){
			throw new RuntimeException("账号重复");
		}
		//检查手机号码
		if (selectCount(new EntityWrapper<User>().ne("id",user.getId()).eq("phone",user.getPhone()))>0){
			throw new RuntimeException("手机号码重复");
		}
		String[] emails = user.getEmails();
		String email = "";
		if(emails != null && emails.length > 0){
			for(int i = 0;i<emails.length; i ++){
				if(i < emails.length -1){
					email = email + emails[i] +",";
				}else{
					email = email + emails[i];
				}
			}
		}
		user.setEmail(email);
		Boolean result = super.insertOrUpdate(user);
		afterSave(user);
		UserUtils.clearCache(user);
		return result;
	}

	@Override
	public boolean insertOrUpdate(String json) {
		User user = JSON.parseObject(json,User.class);
		//账号重复
		if (selectCount(new EntityWrapper<User>().ne("id",user.getId()).eq("username",user.getUsername()))>0){
			throw new RuntimeException("账号重复");
		}
		//检查手机号码
		if (selectCount(new EntityWrapper<User>().ne("id",user.getId()).eq("phone",user.getPhone()))>0){
			throw new RuntimeException("手机号码重复");
		}
		String[] emails = user.getEmails();
		String email = "";
		if(emails != null && emails.length > 0){
			for(int i = 0;i<emails.length; i ++){
				if(i < emails.length -1){
					email = email + emails[i] +",";
				}else{
					email = email + emails[i];
				}
			}
		}
		user.setEmail(email);
		Boolean result = super.insertOrUpdate(user);
		afterSave(user);
		UserUtils.clearCache(user);
		return result;
	}
	@Override
	public Page getListPage(User user) {
		EntityWrapper<User> entityWrapper = new EntityWrapper<>(User.class);
		if (!StringUtils.isEmpty(user.getRealname())) {
			entityWrapper.like("realname", user.getRealname());
		}
		if (!StringUtils.isEmpty(user.getUsername())) {
			entityWrapper.like("username", user.getUsername());
		}
		if (!StringUtils.isEmpty(user.getCode())) {
			entityWrapper.like("code", user.getCode());
		}
		if (!StringUtils.isEmpty(user.getPhone())) {
			entityWrapper.like("phone", user.getPhone());
		}
		Page pageBean = selectPage(PageRequest.getPage(), entityWrapper);
		List<User> users = pageBean.getRecords();
		if(users != null && users.size() > 0){
			for(User bean : users){
				String emails = "";
				if(!StringUtils.isEmpty(bean.getEmail())){
					String[] array = bean.getEmail().split(",");
					for(int i = 0; i < array.length; i++){
						Dict dict = dictService.getByValue(array[i]);
						if(dict != null){
							if(i < array.length -1){
								emails = emails + dict.getLabel() +",";
							}else{
								emails = emails + dict.getLabel();
							}
						}
					}
				}

				if(!emails.equals("")){
					bean.setEmails(emails.split(","));
				}
			}
		}
		return pageBean;
	}

	@Override
	public boolean insert(User user) {
		//账号重复
		if (selectCount(new EntityWrapper<User>().eq("username",user.getUsername()))>0){
			throw new RuntimeException("账号重复");
		}
		//检查手机号码
		if (selectCount(new EntityWrapper<User>().eq("phone",user.getPhone()))>0){
			throw new RuntimeException("手机号码重复");
		}
		passwordService.encryptPassword(user);
		return super.insert(user);
	}

	@Override
	public boolean insertOrUpdate(User user) {
		//账号重复
		if (selectCount(new EntityWrapper<User>().ne("id",user.getId()).eq("username",user.getUsername()))>0){
			throw new RuntimeException("账号重复");
		}
		//检查手机号码
		if (selectCount(new EntityWrapper<User>().ne("id",user.getId()).eq("phone",user.getPhone()))>0){
			throw new RuntimeException("手机号码重复");
		}
		return super.insertOrUpdate(user);
	}

	public void afterSave(User entity) {
		// 删除角色关联
		String[] roleIdList = entity.getRoleIdArray();
		if (roleIdList != null && roleIdList.length > 0) {
			userRoleService.delete(new EntityWrapper<UserRole>(UserRole.class).eq("userId", entity.getId()));
			List<UserRole> userRoleList = new ArrayList<UserRole>();
			for (String roleid : roleIdList) {
				UserRole userRole = new UserRole();
				userRole.setUserId(entity.getId());
				userRole.setRoleId(roleid);
				userRoleList.add(userRole);
			}
			userRoleService.insertBatch(userRoleList);
		}

		// 删除部门关联
		String[] array = entity.getOrganizationIds();
		if(array != null && array.length > 0){
			userOrganizationService.delete(new EntityWrapper<UserOrganization>(UserOrganization.class).eq("userId", entity.getId()));
			List<UserOrganization> userOrganizationList = new ArrayList<UserOrganization>();
			for(String organizationId : array){
				UserOrganization userOrganization = new UserOrganization();
				userOrganization.setUserId(entity.getId());
				userOrganization.setOrganizationId(organizationId);
				userOrganizationList.add(userOrganization);
			}
			userOrganizationService.insertBatch(userOrganizationList);
		}
	}

}
